<template>
  <mu-container class="index">
    <h4>绩点查询</h4>
    <mu-form ref="form" :model="validateForm" class="mu-demo-form">
      <mu-form-item label="学号" help-text="填写山东理工大学学号" prop="username">
        <mu-text-field v-model="validateForm.username" prop="username"></mu-text-field>
      </mu-form-item>
      <mu-form-item label="教务处密码" prop="password">
        <mu-text-field type="password" v-model="validateForm.password" prop="password"></mu-text-field>
      </mu-form-item>
      <mu-form-item prop="isAgree" :rules="argeeRules">
        <mu-checkbox label="同意用户协议" v-model="validateForm.isAgree"></mu-checkbox>
      </mu-form-item>
      <mu-form-item>
        <mu-button color="primary" @click="submit">提交</mu-button>
        <mu-button @click="clear">重置</mu-button>
      </mu-form-item>
    </mu-form>
  </mu-container>
</template>

<script lang="ts">
import { Component, Vue } from "vue-property-decorator";
import Toast from "muse-ui-toast";
import Progress from "muse-ui-progress";
import { ResponseList } from "@/views/Type.ts";

@Component
export default class Index extends Vue {
  usernameRules: Array<object> = [
    { validate: (val: any) => !!val, message: "请务必填写学号" },
    { validate: (val: any) => val.length === 11, message: "很明显学号不正确" }
  ];
  argeeRules: Array<object> = [
    { validate: (val: any) => !!val, message: "必须同意用户协议" }
  ];
  validateForm = {
    username: "",
    password: "",
    isAgree: false
  };

  clear() {
    this.validateForm = {
      username: "",
      password: "",
      isAgree: false
    };
  }

  submit() {
    let _form: any = this.$refs.form;
    console.log(this);
    _form.validate().then((result: boolean) => {
      if (!result) return;
      this.$progress.start();
      fetch("https://study.chaol.top/abc")
        .then(res => res.json())
        .then((data: any) => {
          if (data.code !== 1) {
            this.$toast.message({ message: "网络错误" });
            this.$progress.done();
            return Promise.reject(new Error(data));
          }
          return fetch(
            "http://www.testpj001.xyz/schoolApi/users/score?studentNum=" +
              this.validateForm.username
          );
        })
        .then(res => res.json())
        .then((res: any) => {
          this.$progress.done();
          let _res = res.json();
          if ((<ResponseList>_res).code === 1)
            this.$router.push({
              name: "Detail",
              params: { ..._res }
            });
          else this.$toast.message({ message: "接口错误" });
        })
        .catch(rej => {
          this.$progress.done();
          console.log(rej);
        });
    });
  }
}
</script>

<style scoped>
h3 {
  font-size: 48px;
  font-weight: 400;
}

h4 {
  font-size: 34px;
  font-weight: 400;
}
</style>
